package cn.yuhao.party.theme.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.pager.PageConstants;
import cn.yuhao.party.theme.domain.Theme;

public class ThemeDao {
private QueryRunner qr = new TxQueryRunner();

	
	public PageBean<Theme> findAll(int pc) {
		int ps = PageConstants.BOOK_PAGE_SIZE;// 每页记录数
		String sql = "select * from ubtheme limit ?,?";
		try {
			String sql1 = "select count(*) from ubtheme";
			Number number = (Number) qr.query(sql1, new ScalarHandler());
			int tr = number.intValue();// 得到了总记录数
			List<Theme> listTheme = qr.query(sql,
					new BeanListHandler<Theme>(Theme.class), (pc - 1) * ps,
					ps);
			PageBean<Theme> pb = new PageBean<Theme>();
			/*
			 * 其中PageBean没有url，这个任务由Servlet完成
			 */
			pb.setBeanList(listTheme);
			pb.setPc(pc);
			pb.setPs(ps);
			pb.setTr(tr);

			return pb;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Theme findById(String Gtheme) {
		String sql = "select * from ubtheme where id=?";

		try {
			Theme Theme = (Theme) qr.query(sql, new BeanHandler<Theme>(
					Theme.class), Gtheme);
			return Theme;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void addTheme(Theme Theme) {
		String sql = "insert into ubtheme values(?,?,?,?,?)";
		Object[] params = { Theme.getTheme(),Theme.getTime(),Theme.getPicturn(),Theme.getLink(),Theme.getId()};
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(String Gtheme) {
		String sql = "delete from ubtheme where id=?";
		try {
			qr.update(sql, Gtheme);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void editTheme(Theme Theme) {
		String sql = "update ubtheme set theme=? ,time=? ,picturn=? ,link=? where id=?";
		Object[] params = { Theme.getTheme(),Theme.getTime(),Theme.getPicturn(),Theme.getLink(),Theme.getId() };
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
